package net.celisdelafuente.java.Acacia.entity;

import java.sql.SQLException;
import java.util.ArrayList;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName="suppliers")
public class Supplier {
	
	public static final String ID_FIELD_NAME = "id";
	public static final String NAME_FIELD_NAME = "name";
	public static final String RFC_FIELD_NAME = "rfc";
	
	@DatabaseField(columnName = ID_FIELD_NAME, generatedId = true)
	private int id;
	
	@DatabaseField(columnName = NAME_FIELD_NAME, canBeNull = false)
	private String name;
	
	@DatabaseField(columnName = RFC_FIELD_NAME)
	private String rfc;
	
	public Supplier() {
		// ORMLite needs a no-arg constructor
	}
	
	public Supplier(String name) {
		this.name = name;
	}
	
	public Supplier(String name, String rfc) {
		this.name = name;
		this.rfc = rfc;
	}
	
	public int getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	
	public String getRfc() {
		return rfc;
	}
	
	// TODO Remove this
	/*
	public void setId(int id) {
		this.id = id;
	}
	*/
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setRfc(String rfc) {
		this.rfc = rfc;
	}
	
	@Override
	public int hashCode() {
		return name.hashCode();
	}
	
	@Override
	public boolean equals(Object other) {
		if(other == null || other.getClass() != getClass()) {
			return false;
		}
		return name.equals(((Supplier) other).name);
	}

	@SuppressWarnings("deprecation")
	public Supplier getByName(ConnectionSource conn,
			Dao<Supplier, Integer> dao, String name) {
		Supplier s = this;
		if(!name.isEmpty()) {
			ArrayList<Supplier> supplier = new ArrayList<Supplier>();
			QueryBuilder<Supplier, Integer> qb = dao.queryBuilder();
			try {
				qb.where().eq(Supplier.NAME_FIELD_NAME, name);
				qb.limit(1);
				PreparedQuery<Supplier> pq = qb.prepare();
				supplier = (ArrayList<Supplier>)dao.query(pq);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(!supplier.isEmpty())
				s=supplier.get(0);
		}		
		return s;
	}
}
